package com.eveinfo.api.utils.certificates;

import java.util.LinkedList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import com.eveinfo.api.AbstractApiHandler;

public class CertificatesHandler extends AbstractApiHandler<CertificatesResponse> {

	private LinkedList<String> where;
	
	private ApiCategory category;
	private ApiClass c;
	private ApiCertificate certificate;
	
	public CertificatesHandler() {
		super();
		response = new CertificatesResponse();
		where = new LinkedList<String>();
	}
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		super.startElement(uri, localName, qName, attributes);
		String value = (!localName.equals("")) ? localName : qName;
		if (value.equals("rowset")) {
			where.addFirst(attributes.getValue("name"));
		} else if (value.equals("row")) {
			String first = where.getFirst();
			if (first.equals("categories")) {
				category = new ApiCategory(
						Integer.parseInt(attributes.getValue("categoryID")),
						attributes.getValue("categoryName"));
			} else if (first.equals("classes")) {
				c = new ApiClass(
						Integer.parseInt(attributes.getValue("classID")),
						attributes.getValue("className"));
			} else if (first.equals("certificates")) {
				certificate = new ApiCertificate(
						c.getName(),
						Integer.parseInt(attributes.getValue("certificateID")),
						Integer.parseInt(attributes.getValue("grade")),
						Integer.parseInt(attributes.getValue("corporationID")),
						attributes.getValue("description"));
			} else if (first.equals("requiredSkills")) {
				certificate.addRequiredSkill(
						Integer.parseInt(attributes.getValue("typeID")),
						Integer.parseInt(attributes.getValue("level")));
			} else if (first.equals("requiredCertificates")) {
				certificate.addRequiredCertificate(
						Integer.parseInt(attributes.getValue("certificateID")),
						Integer.parseInt(attributes.getValue("grade")));
			}
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		super.endElement(uri, localName, qName);
		String value = (!localName.equals("")) ? localName : qName;
		if (value.equals("rowset")) {
			where.removeFirst();
		} else if (value.equals("row")) {
			String first = where.getFirst();
			if (first.equals("categories")) {
				response.addCategory(category);
			} else if (first.equals("classes")) {
				category.addClass(c);
			} else if (first.equals("certificates")) {
				c.addCertificate(certificate);
			}
		}
	}

}
